import React, { useContext, useState, useEffect, useRef } from 'react';
import {
  message,
  Drawer,
  Form,
  Input,
  Button,
  Radio,
  InputNumber,
  Tabs,
  Table,
  Spin,
  Popconfirm,
} from 'antd';
import {
  upadataField,
  getMappingByTableid,
  getSqlDetail,
  createStructurebybaseTable,
  savaFile,
} from '../api';

const EditableContext = React.createContext(null);
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

const { TabPane } = Tabs;

const UpdateForm = props => {
  // 结构化数据
  const { visible, onCancel, onSuccess, data, type, currentIndex = 0 } = props;

  // 初始化 form
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [listData, setListData] = useState([]); // 映射字段
  const [sqlData, setSqlData] = useState([]); //sql 语句

  const [itemId, setItemId] = useState();
  // 详情
  const getDetailData = () => {
    const paylaod = {
      id: data.id,
    };
    setLoading(true);

    getMappingByTableid(paylaod).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setItemId(res.data.id);
        const structure = res.data.structures || [];
        setListData(structure);
        // form.setFieldsValue({ ...res.data, ...data })
      } else {
        message.error(res.msg || '获取详情失败');
      }
    });
  };
  // 详情 sql
  const getSqlDetailData = () => {
    const paylaod = {
      id: data.id,
    };
    getSqlDetail(paylaod).then(res => {
      if (res.code === 0) {
        setSqlData(res.data);
        form.setFieldsValue({ ...res.data });
      } else {
        message.error(res.msg || '获取详情失败');
      }
    });
  };

  useEffect(() => {
    if (visible === true) {
      // getDetailData();
      // getSqlDetailData();
    } else {
      form.resetFields();
    }
  }, [visible]);

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = values => {
    const hide = message.loading('正在添加');
    setLoading(true);

    const requirement = values.requirement ? ` where ${values.requirement}` : '';

    const paylaod = {
      comms: `select ${values.fields} from ${sqlData.tableName}${requirement}`,
      current: 1,
      pageSize: 10,
      firstcolumn: sqlData.firstcolumn,
      dataSourceId: sqlData.dataSourceId,
      pri: sqlData.pri,
      type: '1',
      dataUnitId: sqlData.dataUnitId,
    };
    upadataField(paylaod).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '修改失败，请重试');
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then(values => {
      updataData(values);
    });
  };

  const modelClose = () => {
    onCancel(false);
  };

  //生成缺省字段
  const clickCreateStructurebybaseTable = () => {
    setLoading(true);
    createStructurebybaseTable({ id: itemId }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        getDetailData();
      }
    });
  };

  // 页签切换
  const tabChange = () => {};

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const column = [
    {
      title: '列名',
      dataIndex: 'columnName',
      key: 'columnName',
      width: 100,
      editable: true,
    },
    {
      title: '类型',
      dataIndex: 'columnType',
      key: 'columnType',
      width: 100,
      editable: true,
    },
    {
      title: '映射值',
      dataIndex: 'columnValue',
      key: 'columnValue',
      width: 100,
      editable: true,
    },
    {
      title: '备注',
      dataIndex: 'columnComment',
      key: 'columnComment',
      width: 100,
      editable: true,
    },
  ];

  const handleSave = row => {
    const newData = JSON.parse(JSON.stringify(listData));
    const index = newData.findIndex(item => row.id === item.id);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    setListData(newData);
  };

  const columns = column.map(col => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: record => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave: handleSave,
      }),
    };
  });

  //保存

  const save = () => {
    const payload = {
      id: data.id,
      structures: listData,
    };
    savaFile(payload).then(res => {});
  };
  return (
    <>
      <Drawer
        getContainer={false}
        width={940}
        title={type === 'updata' ? '修改' : '添加'}
        visible={visible}
        onClose={modelClose}
        maskClosable={false}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={modelClose} style={{ marginRight: 10 }}>
              取消
            </Button>
          </div>
        }
      >
        <Spin spinning={loading}>
          <div style={{ marginBottom: 10 }}>表名称：{data.tableName}</div>
          <Tabs onChange={tabChange} type="card">
            <TabPane tab="数据结构" key="1">
              <Table
                rowKey={record => record.id}
                components={components}
                columns={columns}
                dataSource={listData}
                bordered
                size="middle"
                pagination={false}
              />
              <div style={{ marginTop: 20 }}>
                对称加密：SM4,DES,3DES,AES,PBE; 非对称加密：SM2,RSA,ElGamal
              </div>
              <div style={{ marginTop: 20 }}>
                <Popconfirm
                  placement="topRight"
                  title="自动生成，将删除已有映射配置，确认要自动生成吗？"
                  onConfirm={clickCreateStructurebybaseTable}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button type="primary">生成缺省字段</Button>
                </Popconfirm>
                <Button type="primary" danger onClick={save} style={{ marginLeft: 20 }}>
                  保存
                </Button>
              </div>
            </TabPane>
            <TabPane tab="数据预览" key="2">
              <Form {...formItemLayout} name="control-ref" form={form}>
                <div style={{ marginBottom: 5 }}>select</div>
                <Form.Item label="" name="fields">
                  <Input.TextArea maxLength={1000} allowClear />
                </Form.Item>
                <div style={{ marginBottom: 5 }}>
                  from <span style={{ fontWeight: 'bold' }}>{sqlData.tableName}</span> where
                </div>
                <Form.Item label="" name="requirement">
                  <Input.TextArea maxLength={1000} allowClear />
                </Form.Item>
              </Form>
              <Button type="primary" onClick={sendData}>
                执行
              </Button>
            </TabPane>
          </Tabs>
        </Spin>
      </Drawer>
    </>
  );
};

export default UpdateForm;
